//
//  YCLEmoticonKeyboard.swift
//  02.表情键盘
//
//  Created by yaochunlin on 16/4/21.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit



class YCLEmoticonKeyboard: UIView {
    
    //设置textview属性
    weak var textView:UITextView?
    
    
    private let identifier = "identifier"
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        let newFrame = CGRect.init(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        
        //自己决定frame值
//        backgroundColor = UIColor.redColor()
        
        //设置ui
        prepareUI()
        
        collectionView.registerClass(YCLEmoticonKeyboardPageCell.self, forCellWithReuseIdentifier: identifier)
        
        //模型数据
//       print("\(YCLEmoticonManager.shareEmoticonManager.allPackages)")
    }
    
    private func prepareUI() {
    
        //添加子控件
        addSubview(emoticonToolBar)
        addSubview(collectionView)
        addSubview(pageControl)
        
        //设置约束
        emoticonToolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        // collectionView 水平,左右和父控件重合
        // H: 水平 V: 垂直
        // ||, |:父控件左边/顶部   |:父控件右边/底部
        // [cv]: 表示一个view  [:view的左边  ]: view的右边
        // views: VFL里面用到的view映射
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: ["cv" : collectionView]))
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: ["tb" : emoticonToolBar]))
        
        // 垂直方向,
        // collectionView的顶部到父控件顶部0
        // collectioView的底部和emoticonToolBar的顶部重合
        // emoticonToolBar高度44
        // emoticonToolBar的底部和父控件的底部重合
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: [], metrics: nil, views: ["cv" : collectionView, "tb": emoticonToolBar]))
        
        //pageControl
        addConstraint(NSLayoutConstraint.init(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint.init(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint.init(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
        
        
    }
    
    //cell的大小等于collectionView的大小
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.bounds.size
        
    }
    
    //MARK: 懒加载控件
    private lazy var emoticonToolBar:YCLEmoticonToolBar = {
    
        let toolBar = YCLEmoticonToolBar.emoticonToolBar()
        
        toolBar.delegate = self
        
        return toolBar
    }()
    
    private lazy var collectionView:UICollectionView = {
    
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //设置滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        //设置水平最小间距
        layout.minimumLineSpacing = 0
        
        //设置分页
        cv.pagingEnabled = true
        cv.bounces = false
        cv.backgroundColor = UIColor.brownColor()
        cv.dataSource = self
        cv.delegate = self
        return cv
        
    }()
    
    //pagecontrol
    private lazy var pageControl: UIPageControl = {
    
        let pc = UIPageControl()
        
//        pc.currentPageIndicatorTintColor = UIColor.init(patternImage: UIImage.init(named: "compose_keyboard_dot_selected")!)
//        pc.pageIndicatorTintColor = UIColor.init(patternImage: UIImage.init(named: "compose_keyboard_dot_normal")!)
        
        //通过kvc给pageControl的属性赋值
        pc.setValue(UIImage.init(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pc.setValue(UIImage.init(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        
//        //TODO: 测试
//        pc.numberOfPages = 5
//        pc.backgroundColor = UIColor.blackColor()
        
//        //由效果可以看到图片平铺来设置currentPageIndicatorTintColor是有问题的
//        //运行时,获取对象所有属性
//        var count: UInt32 = 0
//        let ivars = class_copyIvarList(UIPageControl.self, &count)
//        
//        //遍历
//        for i in 0..<count {
//        
//            //获得每个属性
//            let ivar = ivars[Int(i)]
//            
//            //获取属性名称
//            let cName = ivar_getName(ivar)
//            
//            //转换为字符串
//            let name = String.init(CString: cName, encoding: NSUTF8StringEncoding)
//            
//            print("name: \(name)")
//        }
//        free(ivars)
        

        return pc
    }()
}

//MARK: collectionview数据源和代理
extension YCLEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        
        return YCLEmoticonManager.shareEmoticonManager.allPackages.count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return YCLEmoticonManager.shareEmoticonManager.allPackages[section].pageEmoticons.count
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! YCLEmoticonKeyboardPageCell
//        cell.backgroundColor = UIColor.randomColor()
        //指定代理
        cell.delegate = self
        
        cell.pageEmoticon = YCLEmoticonManager.shareEmoticonManager.allPackages[indexPath.section].pageEmoticons[indexPath.row]
        
        cell.indexPath = indexPath
        
        return cell
        
    }
    
    //滚动到某个组后，滚动到对应的按钮
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //获得中心店
        var centerPoint = scrollView.center
        centerPoint.x += scrollView.contentOffset.x
        
        //判断当前可视cell是否包含可视点
        for cell in collectionView.visibleCells() {
            
            if cell.frame.contains(centerPoint) {
                
                //获取当前cell的indexPath
                let indexPath = collectionView.indexPathForCell(cell)
                
                //通过indexPath获得组数，然后传给toolbar，让按钮滚动到对应的位置
                emoticonToolBar.switchSelectedButtonWithSection((indexPath?.section)!)
                
                setupPageControl(indexPath!)
                
            }
        }
    }
    
    private func setupPageControl(indexPath: NSIndexPath) {
        
        //获得pagecontrol的页数
        pageControl.numberOfPages = YCLEmoticonManager.shareEmoticonManager.allPackages[(indexPath.section)].pageEmoticons.count
        //获取当前页
        pageControl.currentPage = (indexPath.item)
        
        //第0组不需要显示pagecontrol
        pageControl.hidden = indexPath.section == 0
        
    }
}

//MARK: 表情键盘的toolbar中按钮点击代理
extension YCLEmoticonKeyboard: YCLEmoticonToolBarDelegate{

    func emoticonToolBar(toolBar: YCLEmoticonToolBar, didSelectedType type: YCLEmoticonToolBarType) {
        
//        print("点击了\(type)按钮")
        //切换collectionview对应的section
        let indexPath = NSIndexPath.init(forItem: 0, inSection: type.rawValue)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        setupPageControl(indexPath)
    }
}

//MARK: 表情按钮点击的代理方法
extension YCLEmoticonKeyboard: YCLEmoticonKeyboardPageCellDelegate {

    func emoticonKeyboardPageCell(cell: YCLEmoticonKeyboardPageCell, didSelectedEmotion: YCLEmoticonModel) {
        
        //表情按钮被点击
//        print("表情按钮被点击 \(emotion)")
        //将模型内容添加到textview上
        textView!.insertEmoticon(didSelectedEmotion)
        
        YCLEmoticonManager.shareEmoticonManager.addFavorate(didSelectedEmotion)
    }
    
//    //将模型内容添加到textview上
//    private func insertEmoticon(emotion: YCLEmoticonModel) {
//    
//        //1.emoji表情
//        if let emoji = emotion.emoji {
//        
//            textView?.insertText(emoji)
//            return
//        }
//        
//        //2.图片表情
//        
//        if let pngPath = emotion.pngPath {
//            
//            //将图片放到附件中，附件可以添加到属性文本，textview可以显示属性文本
//            let attachment = YCLTextAttachment()
//            attachment.image = UIImage.init(named: pngPath)
//            attachment.chs = emotion.chs
//            
//            //获取文本高度
//            let height = textView?.font?.lineHeight ?? 10
//            
//            //设置附件的大小
//            attachment.bounds = CGRect.init(x: 0, y: -4, width: height, height: height)
//            
//            //属性文本并设置属性文本font
//            let attrString = NSMutableAttributedString.init(attributedString: NSAttributedString.init(attachment: attachment))
//            attrString.addAttribute(NSFontAttributeName, value: (textView?.font)!, range: NSRange.init(location: 0, length: 1))
//            
//            //获取textview现有文本
//            let attrStringM = NSMutableAttributedString.init(attributedString: textView!.attributedText)
//            
//            //光标位置
//            let selectedRange = textView?.selectedRange
//            
//            
//            //替换属性文本到对应的位置
//            attrStringM.replaceCharactersInRange(selectedRange!, withAttributedString: attrString)
//            
//            
//            textView?.attributedText = attrStringM
//            
//            //重新设置光标位置
//            textView?.selectedRange = NSRange.init(location: (selectedRange?.location)! + 1, length: 0)
//            
//        }
//    }
    
    func didSelectDeleteButton() {
        
//        print("删除按钮被点击")
        textView?.deleteBackward()
    }
    
}
